/*
 * Asteroide.cpp
 *
 *  Created on: Apr 5, 2012
 *      Author: gonzalo-Ramiro
 */

#include "Asteroide.h"
#include "../common/lib/SDL_rotozoom.h"
#include "../common/utils/SurfaceUtils.h"

Asteroide::Asteroide(DTOAsteroide* dto) :
		WidgetMovimiento(dto->x, dto->y, dto->tipo->ancho,dto->tipo->alto,dto->tipo->imagePath,NULL) {

	this->angle = dto->tipo->rotacion;
	this->direccion = dto->direccion;
	this->velocity = dto->velocidad;
	this->tipo = new TipoAsteroide(dto->tipo);
}

DTOAsteroide* Asteroide::getDTO() {
	return new DTOAsteroide(tipo->getDTO(),parcel->posX,parcel->posY,direccion,velocity);
}

void Asteroide::setParent(Widget* widget){
	//TODO posible memory leak
	this->parent = widget;
}

void Asteroide::handleEvent(Event event) {
	//NO hacen nada los elementos de juego aún;
}

Asteroide::Asteroide(TipoAsteroide* tipo,int x,int y,int direccion,
		int velocidad, Widget* parent,std::string imagePath) :
		WidgetMovimiento(x, y,imagePath, parent) {

	this->direccion = direccion;
	this->velocity = velocidad;
	this->tipo->imagen = imagePath;
}

void Asteroide::resolve() {
	if(!timer.is_started()){
		timer.start();
	}

	float secsPerFrame = (timer.get_ticks() / 1000.0);

	int posX0 = parcel->posX;
	int posY0 = parcel->posY;
	nextX = parcel->posX;
	nextY = parcel->posY;

	float angleInRadians = angle * (M_PI / 180);

	float velX = velocity * cos(angleInRadians);
	float velY = (-1.0) * velocity * sin(angleInRadians);

	float deltaX = fabs(velX * secsPerFrame);
	deltaX = floor(deltaX * 100) / 100;
	deltaX = floor(deltaX + 0.5);
	float deltaY = fabs(velY * secsPerFrame);
	deltaY = floor(deltaY * 100) / 100;
	deltaY = floor(deltaY + 0.5);

	if(velX >= 0)
		nextX = posX0 + deltaX;
	else if(velX < 0)
		nextX = posX0 - deltaX;

	if (velY >= 0)
		nextY = posY0 + deltaY;
	else if (velY < 0)
		nextY = posY0 - deltaY;

	if(nextX != 0 || nextY != 0)
	{
		parcel->posX = nextX;
		parcel->posY = nextY;
	}

	timer.start();
}

Asteroide::~Asteroide() {
	timer.stop();
}

